import {Component, ViewChild, OnInit} from '@angular/core';
import {FormGroup, AbstractControl, FormBuilder, Validators} from '@angular/forms';
import {Router} from '@angular/router';
import {validateEmail} from '../../theme/validators/email.validator';

import {RegisterCompanyService} from './register-company.service';
import {ModalDirective} from 'ng2-bootstrap';
import {provinces} from '../../constants/provinces';
import {entertypes} from '../../constants/entertypes';

@Component({
  selector: 'water-register-company',
  template: require('./register-company.html'),
  styleUrls: ['./register-company.component.scss']
})
export class RegisterCompanyComponent implements OnInit {
  @ViewChild('smModal') successModal: ModalDirective;

  private registerUrl = '/water/enterpriseSub/register';
  private registerForm: FormGroup;
  private registerInfo: RegisterInfo = new RegisterInfo();

  private fileUploadUrl = '/platform/doc/upload';
  private disableUpload: boolean = false;
  private appLetter: string = 'appLetter';
  private constructionCert: string = 'constructionCert';
  private securityCert: string = 'securityCert';
  private businessLicense: string = 'businessLicense';
  private sizeLimit = 2097152;

  private provinces = provinces;
  private entertypes = entertypes;

  private registerError = false;
  private errorMsg:string;
  private registering = false;

  private validationMessages = {
    'userSub_username': {
      'required': '请填写用户名.',
      'minlength': '用户名至少6个字符长.',
      'maxlength': '用户名不能超过20个字符.'
    },

    'password': {
      'required': '请填写密码.',
      'minlength': '密码至少6个字符.',
      'maxlength': '密码不能超过16个字符.'
    },

    'passwordRepeat': {
      'required': '请填写确认密码.'
    },

    'enterpriseSub_name': {
      'required': '请填写企业名称.',
      'minlength': '企业名称至少4个字符.',
      'maxlength': '企业名称不能超过24个字符.'
    },

    'enterpriseSub_license': {
      'required': '请填写营业执照.',
      'minlength': '营业执照至少4个字符.',
      'maxlength': '营业执照不能超过24个字符.'
    },

    'enterpriseSub_registerarea': {
      'required': '请选择企业注册地'
    },

    'enterpriseSub_entertype': {
      'required': '请选择企业注册地'
    },

    'enterpriseSub_registeredcapital': {
      'required': '请填写注册资金'
    },

    'enterpriseSub_website': {
      'required': '请填写企业网址'
    },

    'enterpriseSub_permitid': {
      'required': '请填写安全生产许可证书编号'
    },

    'enterpriseSub_certificateid': {
      'required': '请填写企业资质证书编号'
    },

    'enterpriseSub_postcode': {
      'required': '请填写邮政编码'
    },

    'enterpriseSub_address': {
      'required': '请填写联系地址'
    },

    'enterpriseSub_contact': {
      'required': '请填写联系人'
    },
    'enterpriseSub_email': {
      // 'required': '请填写联系人邮箱',
      'validateEmail': '邮箱格式不正确'
    },

    'enterpriseSub_legalperson': {
      'required': '请填写法人代表'
    },

    'enterpriseSub_contacttel': {
      'required': '请填写电话号码.',
      'minlength': '电话号码至少8个字符长.',
      'maxlength': '电话号码不能超过11个字符.'
    },
    // TODO 补全校验规则
  };

  private formErrors = {
    'userSub_username': '',
    'password': '',
    'passwordRepeat': '',
    'enterpriseSub_name': '',
    'enterpriseSub_license': '',
    'enterpriseSub_registerarea': '',
    'enterpriseSub_entertype': '',
    'enterpriseSub_registeredcapital': '',
    'enterpriseSub_website': '',
    'enterpriseSub_permitid': '',
    'enterpriseSub_certificateid': '',
    'enterpriseSub_postcode': '',
    'enterpriseSub_address': '',
    'enterpriseSub_contact': '',
    'enterpriseSub_contacttel': '',
    'enterpriseSub_email': '',
    'enterpriseSub_legalperson': '',
    'userInfoSub_telephone': '',

    'companyName': '',
    'bizLicense': '',
    'registeredAddress': '',
    'industry': '',
    'registeredCapital': '',
    'foundAt': '',
    'applicationLetterFileName': '',
    'constructionCertFileName': '',
    'securityCertFileName': '',
    'bizLicenseFileName': '',
    'securityCertNumber': '',
    'zipCode': '',
    'contactAddress': '',
    'contactNumber': '',
    'contactEmail': '',
    'legalRepresentative': ''
  };


  constructor(private _fb: FormBuilder,
              private _registerService: RegisterCompanyService,
              private _router: Router) {
  }

  public ngOnInit() {
    this.buildForm();
  }

  onFileUploading() {
    this.disableUpload = true;
  }

  onFinishUploading(replyObj: any) {
    this.registerInfo[replyObj.property] = replyObj.rsp.data[0].ids;
    this.disableUpload = false;
  }

  buildForm(): void {
    this.registerForm = this._fb.group(
      {
        'userSub_username': [this.registerInfo.userSub_username, [
          Validators.required,
          Validators.minLength(6),
          Validators.maxLength(20)
        ]],
        'password': [this.registerInfo.password, [
          Validators.required,
          Validators.minLength(6),
          Validators.maxLength(16)
        ]],
        'passwordRepeat': [this.registerInfo.passwordRepeat, [
          Validators.required,
        ]],
        'enterpriseSub_name': [this.registerInfo.enterpriseSub_name, [
          Validators.required,
          Validators.minLength(4),
          Validators.maxLength(24)
        ]
        ],
        'enterpriseSub_license': [this.registerInfo.enterpriseSub_license, [
          Validators.required,
          Validators.minLength(4),
          Validators.maxLength(24)
        ]],
        'enterpriseSub_registerarea': [this.registerInfo.enterpriseSub_registerarea, [
          Validators.required
        ]],
        'enterpriseSub_entertype': [this.registerInfo.enterpriseSub_entertype, [
          Validators.required
        ]],
        // 'enterpriseSub_industry': [this.registerInfo.enterpriseSub_industry],
        'enterpriseSub_registeredcapital': [this.registerInfo.enterpriseSub_registeredcapital, [
          Validators.required
        ]],
        'enterpriseSub_establishtime': [this.registerInfo.enterpriseSub_establishtime],
        'enterpriseSub_website': [this.registerInfo.enterpriseSub_website, [
          Validators.required
        ]],
        'enterpriseSub_permitid': [this.registerInfo.enterpriseSub_permitid, [
          Validators.required
        ]],
        'enterpriseSub_certificateid': [this.registerInfo.enterpriseSub_certificateid, [
          Validators.required
        ]],
        'enterpriseSub_postcode': [this.registerInfo.enterpriseSub_postcode, [
          Validators.required
        ]],
        'enterpriseSub_address': [this.registerInfo.enterpriseSub_address, [
          Validators.required
        ]],
        'enterpriseSub_contact': [this.registerInfo.enterpriseSub_contact, [
          Validators.required
        ]],
        'enterpriseSub_contacttel': [this.registerInfo.enterpriseSub_contacttel, [
          Validators.required,
          Validators.minLength(8),
          Validators.maxLength(11)
        ]],
        'enterpriseSub_email': [this.registerInfo.enterpriseSub_email, [
          // Validators.required,
          validateEmail
        ]],
        'enterpriseSub_legalperson': [this.registerInfo.enterpriseSub_legalperson, [
          Validators.required
        ]]
      },
      {validator: this.matchingPasswords('password', 'passwordRepeat')}
    );

    this.registerForm.valueChanges
      .subscribe(data => this.onValueChanged(data));

    this.onValueChanged(); // (re)set validation messages now
  }


  matchingPasswords(passwordKey: string, confirmPasswordKey: string) {
    return (group: FormGroup): {[key: string]: any} => {
      let password = group.controls[passwordKey];
      let confirmPassword = group.controls[confirmPasswordKey];

      if (password.value !== confirmPassword.value) {
        return {
          mismatchedPasswords: true
        };
      }
    }
  }

  onValueChanged(data?: any) {
    if (!this.registerForm) {
      return;
    }
    const form = this.registerForm;
    for (const field in this.formErrors) {

      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  getValue(value:string){
    this.registerInfo.enterpriseSub_industry = value;
  }
  public onSubmit(): void {
    let formData = this.registerForm.value;
    this.registerInfo = Object.assign(this.registerInfo, formData);
    let establishtime: any = document.getElementById('enterpriseSub_establishtime');
    this.registerInfo.enterpriseSub_establishtime = establishtime.value;
    this.registering = true;
    this._registerService.save(this.registerUrl, this.registerInfo).then((function (body) {
      if (body.status === 'success') {
        // 注册成功
        this.registering = false;
        this.showSuccessModal();
      }else if(body.status === 'error'){
        this.registerError = true;
        this.registering = false;
        this.errorMsg = body.data;
      }
    }).bind(this), function () {
      // 注册失败
    });
  }

  showSuccessModal(): void {
    this.successModal.show();
  }

  hideSuccessModal(): void {
    this.successModal.hide();
  }

  redirect(): void {
    this._router.navigateByUrl('/login');
  }

  onHideModal(): void {
    jQuery(".modal-backdrop").remove();
  }
}

export class RegisterInfo {
  userSub_username: string;
  password: string;
  passwordRepeat: string;

  enterpriseSub_name: string;
  enterpriseSub_license: string;
  enterpriseSub_registerarea: string;
  enterpriseSub_entertype: string;
  enterpriseSub_industry: string;
  enterpriseSub_registeredcapital: number;
  enterpriseSub_establishtime: string;
  userInfoSub_telephone: string;
  appLetter: string;
  constructionCert: string;
  securityCert: string;
  businessLicense: string;
  enterpriseSub_permitid: string;
  enterpriseSub_certificateid: string;
  enterpriseSub_postcode: string;
  enterpriseSub_address: string;
  enterpriseSub_contact: string;
  enterpriseSub_contacttel: string;
  enterpriseSub_email: string;
  enterpriseSub_legalperson: string;
  enterpriseSub_website: string;
}
